//
//  HomePageViewController.m
//  MarryMe
//
//  Created by lanou3g on 16/1/9.
//  Copyright © 2016年 revocher. All rights reserved.
//

#import "HomePageViewController.h"
#import "HomeDataHandle.h"
#import "Homemodel.h"
#import "UIView+HB.h"
#import "ImageViewCell.h"
#import "GiftModel.h"
#import "GiftDataHandel.h"
#import "WaterPullViewController.h"
#import "WaterPullDataHandle.h"
#import<CoreLocation/CoreLocation.h>

@class CAEmitterLayer;

@interface HomePageViewController ()<UITableViewDataSource,UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,CLLocationManagerDelegate>
@property (strong,nonatomic) CAEmitterLayer	*heartsEmitter;
@property(strong,nonatomic) UIView * cityView;
@property(strong,nonatomic) UITableView * cityTableView;
@property(strong,nonatomic) UIButton * keyButton;
@property(strong,nonatomic) NSArray *hotCityArray;
@property(strong,nonatomic) UIView * secondView;

@property(strong,nonatomic) UICollectionView *  collectionView;
@property(strong,nonatomic) GiftModel *model;
@property(strong,nonatomic) NSArray *colorArr;
@property(strong,nonatomic) NSArray  * keyIdArr;
@property(strong, nonatomic) CLLocationManager *locationManager;
@property(strong,nonatomic) NSString * currentCity;
@end

@implementation HomePageViewController
-(void)viewWillAppear:(BOOL)animated{
    
    CABasicAnimation *heartsBurst = [CABasicAnimation animationWithKeyPath:@"emitterCells.heart.birthRate"];
    heartsBurst.fromValue		= [NSNumber numberWithFloat:50.0];
    heartsBurst.toValue			= [NSNumber numberWithFloat:  0.0];
    heartsBurst.duration		= 1.0;
    heartsBurst.timingFunction	= [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    
    [self.heartsEmitter addAnimation:heartsBurst forKey:@"heartsBurst"];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    
}
- (void)viewWillUnload
{
    [super viewWillUnload];
    [self.heartsEmitter removeFromSuperlayer];
    self.heartsEmitter = nil;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self animationsView];
    [self collectionViews];
    [self allscrollViews];
    self.secondView = [[UIView alloc]initWithFrame:CGRectMake(0,[UIScreen mainScreen].bounds.size.height , [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    
    self.cityTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width,  [UIScreen mainScreen].bounds.size.height-44) style: UITableViewStyleGrouped ];
    UIView *headerView = [[UIView alloc] initWithFrame: CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 250)];
    headerView.backgroundColor =[UIColor whiteColor];
    self.cityTableView.tableHeaderView = headerView;
    self.cityTableView.delegate = self;
    self.cityTableView.dataSource = self;
    [self.secondView addSubview:self.cityTableView];
    [self allViews];
    [[HomeDataHandle shareHomeDataHandle] getDataFromNet1:^{
        [self.cityTableView reloadData];
        
    }];
    [self secondViews];
    [self.view addSubview:self.secondView];
    //collectionView回调
    [[GiftDataHandel shareGiftDataHandle] getDataFromNet1:^{
        [self.collectionView reloadData];
    }];
    
}
#pragma mark --- 布局collectionView
-(void)collectionViews{
    //1创建layout对象
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    //2配置属性
    //(2.1设置行间距(每个item上下距离)
    layout.minimumLineSpacing = 10;
    //(2.2设置左右间距(列间距
    layout.minimumInteritemSpacing =5;//>=50
    //(2.3 设置item的size
    layout.itemSize = CGSizeMake([UIScreen mainScreen].bounds.size.width/2-20,170);
    //(2.4设置距屏幕边缘的距离
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    
    //3创建 UICollectionView
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 120, [UIScreen mainScreen].bounds.size.width,  [UIScreen mainScreen].bounds.size.height-120) collectionViewLayout:layout];
    //4添加到父视图
    [self.view addSubview:self.collectionView];
    //5遵守协议 实现方法
    //设置代理
    self.collectionView.backgroundColor =[UIColor whiteColor];
    
    self.collectionView.dataSource =self;
    self.collectionView.delegate = self;
    
}
#pragma mark --布局 scrollView
-(void)allscrollViews{
    UIScrollView * scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, 50)];
    scrollView.contentSize = CGSizeMake([UIScreen mainScreen].bounds.size.width*2, 50);
    scrollView.showsHorizontalScrollIndicator = NO;
    
    [self.view addSubview:scrollView];
    self.colorArr = @[@"红色婚礼",@"玫红色婚礼",@"橙色婚礼",@"黄色婚礼",@"薄荷绿色婚礼",@"粉红婚礼",@"墨绿婚礼",@"青蓝婚礼",@"天蓝婚礼",@"宝蓝色婚礼",@"浅紫色婚礼",@"深紫色婚礼",@"褐色婚礼",@"金色婚礼",@"裸色婚礼",@"灰色婚礼",@"白色婚礼",@"黑色婚礼"];
    self.keyIdArr = @[@"f26060",@"f15d94",@"ffaf61",@"f7de6a",@"B4EEB4",@"fdb0b0",@"008B00",@"66cccc",@"3CB3EB",@"0304e5",@"EEAEEE",@"C71585",@"b06f18",@"ffd700",@"f6d5b2",@"CFCFCF",@"fefefe",@"000000"];
    
    for (int i = 0; i<18; i++) {
        UIButton *button = [UIButton buttonWithType: UIButtonTypeCustom];
        [button setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%d.png",i]] forState:  UIControlStateNormal];
        
        NSInteger X = [UIScreen mainScreen].bounds.size.width/9;
        
        button.frame = CGRectMake(X*i +20, 20, 32, 32);
        button.tag = i+100;
        [button addTarget:self action:@selector(colorClickAction:) forControlEvents:    UIControlEventTouchUpInside ];
        [scrollView addSubview:button];
    }
    
}

#pragma mark -- 颜色点击事件
-(void)colorClickAction:(UIButton *)sender{
    [WaterPullDataHandle shareWaterPullDataHandle].urlstr = [NSString stringWithFormat:@"http://www.lovewith.me/app/v020/search/color?page=1&q=%@&token=eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJzdGF0dXMiOiAyLCAidXNlcl9pZCI6IDM3NDcxLCAiZXhwIjogMTQ4MzQyNzYyOC4xNjQyMTV9.8zajgFu7Hkgsy1pa5xRuTlV98YkhtPWbKL0tdmR4WrE",self.keyIdArr[sender.tag-100]];
    WatelPullViewController * waterVC = [[WatelPullViewController alloc]init];
    waterVC.title = self.colorArr[sender.tag-100];
    [self.navigationController  pushViewController:waterVC animated:YES];
    [self.navigationController setNavigationBarHidden:NO];
}

#pragma mark  -- 实现代理方法 UICollectionViewDelegate
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    //初始化xib cell视图
    UINib *nib = [UINib nibWithNibName:@"ImageViewCell"
                                bundle: [NSBundle mainBundle]];
    [collectionView registerNib:nib forCellWithReuseIdentifier:@"ImageViewCell"];
    ImageViewCell *cell = [[ImageViewCell alloc]init];
    
    // Set up the reuse identifier
    cell = [collectionView dequeueReusableCellWithReuseIdentifier: @"ImageViewCell"
                                                     forIndexPath:indexPath];
    self.model = [GiftDataHandel shareGiftDataHandle].giftDataArray[indexPath.row];
    
    [cell setcellDataWithGiftModel:self.model];
    
    return cell;
    
}


//是否可以点击
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return [GiftDataHandel shareGiftDataHandle].giftDataArray.count;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    self.model = [GiftDataHandel shareGiftDataHandle].giftDataArray[indexPath.row];
    [WaterPullDataHandle shareWaterPullDataHandle].urlstr = [NSString stringWithFormat:@"http://www.lovewith.me/app/v020/search/tag/?page=1&q=%@&token=",[self.model.tag stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
    WatelPullViewController * waterVC = [[WatelPullViewController alloc]init];
    waterVC.title = self.model.tag;
    [self.navigationController pushViewController:waterVC animated:YES];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
    
    
    
}

#pragma mark -- 布局界面
-(void)secondViews{
    NSInteger X = ([UIScreen mainScreen].bounds.size.width-60)/3;
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 70, 80, 20)];
    label.text = @"当前所在";
    [self.cityTableView.tableHeaderView addSubview:label];
    UIButton * buttonLocal = [UIButton buttonWithType:UIButtonTypeSystem];
    buttonLocal.frame = CGRectMake(10, 90, X, 25);
    [buttonLocal setTitle:@"北京" forState: UIControlStateNormal  ];
    [buttonLocal addTarget:self action:@selector(buttonClickedAction1:) forControlEvents: UIControlEventTouchUpInside ];
    [self.cityTableView.tableHeaderView addSubview:buttonLocal];
    UIButton * buttonAllCity = [UIButton buttonWithType:UIButtonTypeSystem];
    buttonAllCity.frame = CGRectMake(X+20, 90, X, 25);
    [buttonAllCity setTitle:@"全国" forState: UIControlStateNormal  ];
    [buttonAllCity addTarget:self action:@selector(buttonClickedAction2:) forControlEvents: UIControlEventTouchUpInside ];
    [self.cityTableView.tableHeaderView addSubview:buttonAllCity];
    UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(10,110, 120, 20)];
    label1.text = @"国内热门城市";
    [self.cityTableView.tableHeaderView addSubview:label1];
    
    for (int i = 0; i<_hotCityArray.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake((X+10)*(i%3)+10,30*(i/3)+130 ,X, 30);
        [button setTitle:_hotCityArray[i] forState:    UIControlStateNormal ];
        [button addTarget:self action:@selector(buttonClickedAction:) forControlEvents: UIControlEventTouchUpInside ];
        button.tag = i;
        [self.cityTableView.tableHeaderView addSubview:button];
    }
    
    
}


#pragma mark -- 布局界面
-(void)allViews{
    self.hotCityArray  = @[@"杭州",@"北京",@"上海",@"成都",@"深圳",@"西安",@"南京",@"武汉",@"广州",@"苏州",@"三亚",@"重庆"];
    UIView * topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 64)];
    topView.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:topView];
    self.keyButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.keyButton.frame = CGRectMake(10, 20, 80, 25);
    [self.keyButton setTitle:@"北京" forState: UIControlStateNormal  ];
    [self.keyButton addTarget:self action:@selector(keyButtonClickedAction:) forControlEvents: UIControlEventTouchUpInside ];
    [topView addSubview:self.keyButton];
    
    
    
    UIView * quitView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 64)];
    quitView.backgroundColor = [UIColor redColor];
    [self.secondView addSubview:quitView];
    UIButton *quitButton = [UIButton buttonWithType:    UIButtonTypeSystem];
    quitButton.frame = CGRectMake(35, 24, 16, 16);
    [quitButton setImage:[UIImage imageNamed:@"xx.png"] forState:   UIControlStateNormal];
    [quitButton addTarget:self action:@selector(quitButtonAction:) forControlEvents:  UIControlEventTouchUpInside ];
    [quitView addSubview:quitButton];
    
}



#pragma mark 左上角的button
-(void)keyButtonClickedAction:(UIButton*)sender{
    self.tabBarController.tabBar.hidden = YES;
    [UIView transitionWithView:self.view duration:1 options:    UIViewAnimationOptionLayoutSubviews  animations:^{
        self.secondView.y = 0;
    } completion:^(BOOL finished) {
        
    }];
    
    
    
    
}
#pragma mark quitButton点击事件
-(void)quitButtonAction:(UIButton *)sender{
    [UIView transitionWithView:self.view duration:1 options:    UIViewAnimationOptionLayoutSubviews  animations:^{
        self.secondView.y = self.secondView.y +[UIScreen mainScreen].bounds.size.height;
        
    } completion:^(BOOL finished) {
        self.tabBarController.tabBar.hidden = NO;
    }];
    
    
    
}


#pragma mark ----- button 点击事件
-(void)buttonClickedAction:(UIButton *)sender{
    [self.keyButton setTitle:self.hotCityArray[sender.tag]  forState: UIControlStateNormal  ];
    [UIView transitionWithView:self.view duration:1 options:    UIViewAnimationOptionLayoutSubviews  animations:^{
        self.secondView.y = self.secondView.y +[UIScreen mainScreen].bounds.size.height;
        
    } completion:^(BOOL finished) {
        self.tabBarController.tabBar.hidden = NO;
    }];
    
}
-(void)buttonClickedAction1:(UIButton *)sender{
    [self.keyButton setTitle:@"北京" forState: UIControlStateNormal  ];
    [UIView transitionWithView:self.view duration:1 options:    UIViewAnimationOptionLayoutSubviews  animations:^{
        self.secondView.y = self.secondView.y + [UIScreen mainScreen].bounds.size.height;
        
    } completion:^(BOOL finished) {
        self.tabBarController.tabBar.hidden = NO;
    }];
}
-(void)buttonClickedAction2:(UIButton *)sender{
    [self.keyButton setTitle:@"全国" forState: UIControlStateNormal  ];
    [UIView transitionWithView:self.view duration:1 options:    UIViewAnimationOptionLayoutSubviews  animations:^{
        self.secondView.y = self.secondView.y + [UIScreen mainScreen].bounds.size.height;
        
    } completion:^(BOOL finished) {
        self.tabBarController.tabBar.hidden = NO;
    }];
    
}



#pragma mark -- tableView代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [[HomeDataHandle shareHomeDataHandle].listDataArray[section] count];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return [HomeDataHandle shareHomeDataHandle].keyArray.count;
    
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cell_id  = @"HomePageViewController";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cell_id];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cell_id];
    }
    Homemodel *model = [HomeDataHandle shareHomeDataHandle].listDataArray[indexPath.section][indexPath.row];
    cell.textLabel.text = model.name;
    return cell;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return [HomeDataHandle shareHomeDataHandle].keyArray[section];
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 20;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40;
}
//索引
-(NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    return [HomeDataHandle shareHomeDataHandle].keyArray;
    
}
//锁定事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    Homemodel *model = [HomeDataHandle shareHomeDataHandle].listDataArray[indexPath.section][indexPath.row];
    [self.keyButton setTitle:model.name forState: UIControlStateNormal  ];
    [UIView transitionWithView:self.view duration:1 options:    UIViewAnimationOptionLayoutSubviews  animations:^{
        self.secondView.y = self.secondView.y + [UIScreen mainScreen].bounds.size.height;
        
    } completion:^(BOOL finished) {
        self.tabBarController.tabBar.hidden = NO;
    }];
    
    ////改动
    NSLog(@"+++++++%@",model.cid);
    
    NSDictionary *dic = [NSDictionary dictionaryWithObject:model.cid forKey:@"cityName"];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"city" object:nil userInfo:dic];
}







#pragma mark 配置动画
-(void)animationsView{
    self.heartsEmitter = [CAEmitterLayer layer];
    self.heartsEmitter.emitterPosition = CGPointMake([UIScreen mainScreen].bounds.size.width/2,
                                                     [UIScreen mainScreen].bounds.size.height-100);
    self.heartsEmitter.emitterMode = kCAEmitterLayerVolume;
    self.heartsEmitter.emitterShape = kCAEmitterLayerRectangle;
    self.heartsEmitter.renderMode = kCAEmitterLayerAdditive;
    
    CAEmitterCell *heart = [CAEmitterCell emitterCell];
    heart.name = @"heart";
    heart.emissionLongitude = M_PI/2.0;
    heart.emissionRange = 0.55 * M_PI;
    heart.birthRate		= 0.0;
    heart.lifetime		= 8.0;
    heart.velocity		= -120;
    heart.velocityRange = 60;
    heart.yAcceleration = 20;
    heart.contents		= (id) [[UIImage imageNamed:@"PooHeart"] CGImage];
    heart.color			= [[UIColor colorWithRed:0.5 green:0.0 blue:0.5 alpha:0.5] CGColor];
    heart.redRange		= 0.3;
    heart.blueRange		= 0.3;
    heart.alphaSpeed	= -0.5 / heart.lifetime;
    heart.scale			= 0.15;
    heart.scaleSpeed	= 0.5;
    heart.spinRange		= 2.0 * M_PI;
    
    self.heartsEmitter.emitterCells = [NSArray arrayWithObject:heart];
    [self.view.layer addSublayer:self.heartsEmitter];
    
    
}
#pragma mark - 获取当前定位城市

- (void)locate {
    self.currentCity = [[NSString alloc] init];
    // 判断是否开启定位
    if ([CLLocationManager locationServicesEnabled]) {
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
        [self.locationManager startUpdatingLocation];
    } else {
        NSLog(@"定位失败");
        
        
    }
}


@end
